import React, { memo, useRef } from "react";
import { Editor } from "@tinymce/tinymce-react";
import { genWidget } from "../core";
import { Form } from "antd";
import ItemLayout, { WrapProps } from "./formLabel";

export const genRichTextWidget = (c: WidgetCategory): RichTextWidget => {
  const base = genWidget(c);
  return {
    ...base,
    label: "富文本",
    placeholder: "请输入",
  };
};

const RichEle: React.FC<{
  value?: string;
  onChange?(value: string): void;
  isview?: boolean;
}> = memo((props) => {
  const editorRef = useRef<any>(null);
  return (
    <Editor
      onInit={(_, editor) => (editorRef.current = editor)}
      initialValue={props.value}
      tinymceScriptSrc={process.env.PUBLIC_URL + "/tinyMCE/tinymce.min.js"}
      disabled={!props.isview}
      init={{
        height: props.isview ? "400px" : "100%",
        language: "zh_CN", //调用放在langs文件夹内的语言包
        plugins:
          "preview searchreplace autolink directionality visualblocks visualchars fullscreen link media template codesample table charmap pagebreak nonbreaking anchor insertdatetime advlist lists wordcount image help emoticons autosave",
        toolbar: `undo redo | cut copy paste  pastetext | lineheight forecolor backcolor bold italic underline strikethrough code link anchor | alignleft aligncenter alignright alignjustify outdent indent |
              styleselect formatselect fontselect fontsizeselect | bullist numlist | blockquote subscript superscript removeformat |
              table image media charmap emoticons hr pagebreak insertdatetime preview | fullscreen `,
        branding: false,
        resize: false,
      }}
      onSubmit={() => {
        const value = editorRef.current?.getContent() as string;
        props.onChange && props.onChange(value);
      }}
    ></Editor>
  );
});

const RichWidgetRender = (props: WrapProps<RichTextWidget>) => {
  const { name, isRequired, placeholder, isview } = props;
  return (
    <ItemLayout {...props}>
      {!isview && <RichEle isview={isview} />}
      {isview && (
        <Form.Item
          name={name}
          required={isRequired}
          rules={[
            {
              required: isRequired,
              message: placeholder,
            },
          ]}
        >
          <RichEle isview={props.isview} />
        </Form.Item>
      )}
    </ItemLayout>
  );
};

export default RichWidgetRender;
